from fastapi import APIRouter,Depends
from sqlalchemy import desc,asc,and_
from model.downmine_data import DownmineData
from model.equipment_drill import EquipmentDrill
from model.equipment_sensor import EquipmentSensorTable
from sqlalchemy.orm import Session
from db.mysql import get_db
from vendor.extend.courier import *
from vendor.library.many_points_stress.sort_point import process_wavelength_data
from vendor.library.many_points_stress.many_points_stress import calculate_stress_points
from vendor.extend.conversion import is_positive_integer,is_index_valid

Downmine = APIRouter()

@Downmine.get('/sensor')
async def sensor(sensor_id:int=0,start_time:int=0,end_time:int=0, db: Session = Depends(get_db)):
    if not is_positive_integer(sensor_id):
        return Error(msg='传感器id参数错误')
    if end_time<start_time:
        return Error(msg='结束时间不能小于开始时间')
    if not is_positive_integer(start_time):
        end_time=int(time.time())
        start_time=end_time-604800

    detector=db.query(EquipmentSensorTable.id,EquipmentSensorTable.drill_id,EquipmentSensorTable.raster_data).filter_by(id=sensor_id).first()
    if not detector:
        return Error(msg='传感器不存在')
    data_time=db.query(DownmineData.create_time).order_by(asc("id")).first()
    if not data_time:
        return Error(msg='检测数据未找到')
    initial_time=(data_time.create_time+300)
    # 传入的光栅点比例系数（由深入浅）
    coefficients = [0.5, 0.6, 0.7, 0.8, 0.9, 1.0, 1.1, 1.2, 1.3, 1.4]
    # 获得所有光栅1设计波长λ
    dict_data = [row['factor'] for row in detector.raster_data]
    # 获得所有光栅1设计波长λ
    wavelength_data = [row['wavelength'] for row in detector.raster_data]
    # 每个光栅深度
    depth_data = [row['depth'] for row in detector.raster_data]
    # 生成10个数组
    design_wavelengths=[0 for _ in range(9)]
    # 传入的设计波长 后台配置， 覆盖前面的数组，至少数组中有10个数字，不足为0
    design_wavelengths[0:len(wavelength_data)]=wavelength_data
    coefficients[0:len(dict_data)]=dict_data
    drill=db.query(EquipmentDrill.id,EquipmentDrill.channel).filter_by(id=detector.drill_id).order_by(desc("id")).first()
    if not drill:
        return Error(msg='钻孔不存在')

    # 传入的通道名称数据
    channel_num = drill.channel.lower()
    #channel_num='ch2'
    # ch2 = channel_num[:2]
    #
    # if ch2 !='ch':
    #     return Error(msg='通道参数错误')


    last_info=db.query(DownmineData.data).filter(and_(DownmineData.line == channel_num,DownmineData.create_time > initial_time)).order_by(asc("id")).first()
    if not last_info:
        return Error(msg='没有找到相关数据')
    # 截取的初始波长 历史数据开始五分钟后第一条数据
    initial_wavelengths=last_info.data[0:10]
    #initial_wavelengths = [1529.948, 1533.435, 1540.348, 1536.698, 1547.937, 1543.769, 1551.826, 1555.261, 1558.858, 1562.280]
    list_data=db.query(DownmineData.data,DownmineData.line,DownmineData.create_time).filter_by(line=channel_num).filter(and_(DownmineData.create_time < end_time,DownmineData.create_time > start_time)).order_by(asc("id")).all()

    list_len=len(list_data)
    data_list=[]
    if list_len>500:
        start = 0
        end = list_len-1
        count = 500
        interval = (end - start) / (count - 1)  # 计算间隔
        keys = [int(start + i * interval) for i in range(count)]
        data_list = [list_data[i] for i in keys]
    else:
        data_list=list_data
    raw_wavelength_data={}
    data_array=[]
    # 传入的点数
    point_num = 10
    raw_wavelength_data[channel_num]=initial_wavelengths
    analysis_report, processed_data, need_analysis, abnormal_positions= process_wavelength_data(design_wavelengths, raw_wavelength_data, point_num, channel_num)
    initial_wavelengths=processed_data
    for row in data_list:

        # 传入的通道名称数据
        #channel_num = 'ch2'

        # 波长数据
        raw_wavelength_data[row.line]=row.data

        # 运行处理
        analysis_report, processed_data, need_analysis, abnormal_positions= process_wavelength_data(design_wavelengths, raw_wavelength_data, point_num, channel_num)
        # print("\n直接返回的结果:")
        # print(f"分析报告: {analysis_report}")
        # print(f"排序后的数据: {processed_data}")
        # print(f"是否需要分析: {need_analysis}")
        # 排序后的数据
        processed_data = processed_data
        # print(processed_data)
        # 截取的初始波长 历史数据开始五分钟后第一条数据
        #initial_wavelengths = [1529.948, 1533.435, 1540.348, 1536.698, 1547.937, 1543.769, 1551.826, 1555.261, 1558.858, 1562.280]
        # 传入的光栅点比例系数（由深入浅）
        #coefficients = [0.5, 0.6, 0.7, 0.8, 0.9, 1.0, 1.1, 1.2, 1.3, 1.4]
        # 计算调整后的值
        adjusted_values = calculate_stress_points(processed_data, initial_wavelengths, coefficients)
        # print(adjusted_values)
        # print("\n最终结果:")
        # print(f"排序后的数据: {[f'{x:.3f}' if x is not None else None for x in processed_data]}")
        # print(f"计算的应力值: {[f'{x:.6f}' if x is not None else None for x in adjusted_values]}")
        stress=[]
        for index, item in enumerate(adjusted_values):
            depth=0
            if is_index_valid(depth_data,index):
                depth=depth_data[index]

            stress.append({
                'depth':depth,
                'stress':item
            })
        data_array.append({'create_time': row.create_time, 'stress':stress,'stress_value': adjusted_values})

    return Success(data=data_array)


